const app = getApp();
let tool = require('../../utils/tool.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasSel: {},
    percent: 0,
    totalNum: 0,
    imageUrl: app.globalData.imageurl,
    gameSecond: 15,
    worldList: {},
    curIndex: 0,
    innerAudioContext: new Object(),
    timer: '',
    wordID: 0,
    wordLen: 0,
    wordCur: {},
    listDatas: {},
    allWord: '',
    errWord: '',
    canClick: 0,
    ishide: "1",
    date:'', //学习日期
  },
  //倒计时
  daojishi: function() {
    let that = this;
    that.data.timer = setInterval(function() {
      let num = parseInt(that.data.gameSecond) - 1;
      let cid = that.data.curIndex + 1;
      if (num < 10 && num >= 0) {
        num = "0" + num.toString();
      }
      that.setData({
        gameSecond: num,
        curIndex: cid,

      });

      if (parseInt(that.data.gameSecond) <= 0) {
        that.addErrWord(that.data.wordCur.id)
        if (that.data.wordID < (that.data.wordLen - 1)) {
          that.playNext();
        } else {
          clearInterval(that.data.timer);
          that.submitAnswer();
        }
      }
    }, 1000);

  },
  playNext: function() {
    this.data.innerAudioContext.stop();

    this.setData({
      allWord: this.data.allWord + "," + this.data.listDatas[(this.data.wordID + 1)].id,
      wordCur: this.data.listDatas[(this.data.wordID + 1)],
      wordID: this.data.wordID + 1,
      curIndex: 0,
      // percent: 0,
      totalNum: 15,
      gameSecond: 15,
      hasSel: {},
      canClick: 0,
      percent: parseInt(100 / this.data.wordLen * (this.data.wordID + 2))
    });
 
    this.playMp3(this.data.wordCur.vedio_url);

  },
  playOne: function() {
    this.playMp3(this.data.wordCur.vedio_url);
  },
  submitAnswer: function() {
    var that = this;
    let errWords= that.data.errWord.split(",");
    let errorlist = Array.from(new Set(errWords));
     console.log("submit-errword="+errorlist.join(','))
    let bodyParam = {
      errword: errorlist.join(','),
      allword: that.data.allWord,
      type: '2',
      // access_token:app.globalData.access_token
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      date: that.data.date
    }
    let rs = tool.getSign(bodyParam, app.globalData.key); //返回 bodyParam heaer sign
    let urlStr = app.globalData.apiURL + "review/upresult?sign=" + rs.sign;

    let getAns = new Promise(function(reslove, reject) {
      wx.request({
        url: urlStr,
        header: rs.header,
        data: rs.bodyParam,
        method: 'post',
        success(res) {
          console.log(res);
          reslove(res);
        }
      })

    });
    getAns.then(function(res) {
      if (res.data.code !== 1) {
        wx.showToast({
          title: res.data.info,
          icon: 'none',
          duration: 2000
        })
      } else {

        wx.redirectTo({
          url: '../listenWorld/lworldReport/lworldReport?data=' +
            JSON.stringify(res.data.data) + '&type=2',
        });

      }
    })
  },
  clickTxt: function(e) {
    let that=this;
    if (this.data.canClick === 1) {
      return;
    }
    this.setData({
      canClick: 1
    })
    let temID = e.currentTarget.dataset.index;
    let temArr = {};
    temArr[this.data.wordCur.right] = 'v1-1-ok';
    if (temID == this.data.wordCur.right) {
      this.playMp3(app.globalData.mp3.gamesuccess);
    } else {
      this.addErrWord(this.data.wordCur.id)
      temArr[temID] = 'v1-1-err';
      this.playMp3(app.globalData.mp3.selectwrong);
    }
    this.setData({
      hasSel: temArr
    })
    if (this.data.wordID >= (this.data.wordLen - 1)) {
      clearInterval(this.data.timer);
      this.submitAnswer();

    } else {
      let that = this;
      setTimeout(function() {
        that.playNext()
      }, 1000);
    }


  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    //获取传过来的日期
    that.setData({
      date: options.date,
    })
   console.log(that.data.date)
    try {
      let value = wx.getStorageSync('lword2')
      if (value) {
        wx.redirectTo({
          url: '../listenWorld/lworldWrong/lworldWrong?type=2',
        });
        return;
      }
    } catch (e) {
      console.log(e);
    }
    this.data.innerAudioContext = wx.createInnerAudioContext()
    this.data.innerAudioContext.autoplay = false;
    this.data.innerAudioContext.loop = false;
    this.getData();

  },
  playMp3: function(url) {
    this.data.innerAudioContext.src = url;
    this.data.innerAudioContext.play();
  },
  addErrWord: function(errData) {
    let temWrod = this.data.errWord;
    if (temWrod === "") {
      temWrod = errData;
    } else {
      temWrod = temWrod + "," + errData;
    }
    this.setData({
      errWord: temWrod
    })
  },



  getData: function() {
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    let paramArr = {
      // access_token:app.globalData.access_token
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      date:that.data.date
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "review/meaning?sign=" + sign;
    let classPro = new Promise(
      function(resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }

    );
    classPro.then(function(res) {
      wx.hideLoading();
      if (res.data.code === 1) {
        console.log(res);
        console.log(res.data.data)
        that.setData({

          listDatas: res.data.data.word[0],
          wordLen: res.data.data.word[0].length,
          wordCur: res.data.data.word[0][0],
          allWord: res.data.data.word[0][0].id,
          percent: parseInt(100 / res.data.data.word[0].length * 1)
        });
      }

      that.daojishi();
      that.playMp3(that.data.wordCur.vedio_url);
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.ishide == 2) {
      this.setData({
        ishide: 1
      })
      this.daojishi();
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      ishide: 2
    })
    clearInterval(this.data.timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(this.data.timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  gotourl: (e) => {
    wx.navigateTo({
      url: e.currentTarget.dataset.urldata,
    });
  }
})